1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package java.nio.charset;
18
19 import java.util.Collections;
20 import java.util.SortedMap;
21 import java.util.TreeMap;
22
23
24
25
26
27
28 public abstract class Charset implements Comparable<Charset> {
29 private static final Charset UTF_8 = new Charset("UTF-8") {};
30
31 private static final SortedMap<String, Charset> AVAILABLE_CHARSETS =
32 new TreeMap<String, Charset>();
33 static {
34 AVAILABLE_CHARSETS.put(UTF_8.name(), UTF_8);
35 }
36
37 public static SortedMap<String, Charset> availableCharsets() {
38 return Collections.unmodifiableSortedMap(AVAILABLE_CHARSETS);
39 }
40
41 public static Charset forName(String charsetName) {
42 if (charsetName == null) {
43 throw new IllegalArgumentException("Null charset name");
44 }
45 int length = charsetName.length();
46 if (length == 0) {
47 throw new IllegalCharsetNameException(charsetName);
48 }
49 for (int i = 0; i < length; i++) {
50 char c = charsetName.charAt(i);
51 if ((c >= 'A' && c <= 'Z')
52 || (c >= 'a' && c <= 'z')
53 || (c >= '0' && c <= '9')
54 || (c == '-' && i != 0)
55 || (c == ':' && i != 0)
56 || (c == '_' && i != 0)
57 || (c == '.' && i != 0)) {
58 continue;
59 }
60 throw new IllegalCharsetNameException(charsetName);
61 }
62 Charset charset = AVAILABLE_CHARSETS.get(charsetName.toUpperCase());
63 if (charset != null) {
64 return charset;
65 }
66 throw new UnsupportedCharsetException(charsetName);
67 }
68
69 private final String name;
70
71 private Charset(String name) {
72 this.name = name;
73 }
74
75 public final String name() {
76 return name;
77 }
78
79 public final int compareTo(Charset that) {
80 return this.name.compareToIgnoreCase(that.name);
81 }
82
83 public final int hashCode() {
84 return name.hashCode();
85 }
86
87 public final boolean equals(Object o) {
88 if (o == this) {
89 return true;
90 } else if (o instanceof Charset) {
91 Charset that = (Charset) o;
92 return this.name.equals(that.name);
93 } else {
94 return false;
95 }
96 }
97
98 public final String toString() {
99 return name;
100 }
101 }